package com.leyou.Controller;


import com.leyou.Service.BrandService;
import com.leyou.PageResult;
import item.pojo.Brand;
import item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> queryBrandByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,//当前页
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,//每页大小
            @RequestParam(value = "sortBy", required = false) String sortBy,//排序字段
            @RequestParam(value = "desc", defaultValue = "false") Boolean desc,//是否降序
            @RequestParam(value = "key", required = false) String key) {
        PageResult<Brand> result =
                this.brandService.queryBrandByPageAndSort(page, rows, sortBy, desc, key);

        if (result != null && 0 != result.getItems().size()) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
        // 测试参数是否能传递
//        System.out.println("brand = " + brand);
//        System.out.println("cids = " + cids);

        this.brandService.saveBrand(brand, cids);

        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping
    public ResponseEntity<Void> uploadBrand(Brand brand,@RequestParam("cids") List<Long> cids){

        this.brandService.uploadBrand(brand,cids);

        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //删除
    @GetMapping("deletebid/{bid}")
    public ResponseEntity<List<Category>> deteleByBrandId(@PathVariable("bid") Long bid){
        this.brandService.deleteByBrandId(bid);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandByCategory(@PathVariable("cid") Long cid) {
        List<Brand> list = this.brandService.queryBrandByCategory(cid);
        if(list == null||list.size()==0){
            new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(list);
    }

    @GetMapping("bid/{bid}")
    public ResponseEntity<Brand> queryBrandById(@PathVariable("bid")Long bid){
        Brand brand = this.brandService.queryBrandById(bid);
        if (brand != null) {
            return ResponseEntity.ok(brand);
        }

        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


}
